// 全局变量
let selectedProtocol = 'chargingPile';

// DOM元素
const resizeHandle = document.getElementById('resizeHandle');
const leftPanel = document.querySelector('.left-panel');
const container = document.querySelector('.resizable-container');
const resultResizeHandle = document.getElementById('resultResizeHandle');
const resultTop = document.querySelector('.result-top');
const resultContainer = document.querySelector('.result-container');

// 拖拽状态变量
let isResizing = false;
let startX, startLeftWidth;
let isResultResizing = false;
let startY, startTopHeight;

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    initializeEventListeners();
    initializeResizeHandlers();
});

// 初始化事件监听器
function initializeEventListeners() {
    // 协议选择下拉框
    document.getElementById('protocolSelect').addEventListener('change', function() {
        selectedProtocol = this.value;
    });

    // 解析按钮
    document.getElementById('parseBtn').addEventListener('click', parseProtocol);

    // 清空按钮
    document.getElementById('clearBtn').addEventListener('click', clearAll);

    // 复制JSON按钮
    document.getElementById('copyJsonBtn').addEventListener('click', copyJsonToClipboard);

    // 快捷键支持
    document.addEventListener('keydown', handleKeyboardShortcuts);
}

// 初始化拖拽处理器
function initializeResizeHandlers() {
    // 左右面板拖拽调整宽度功能
    resizeHandle.addEventListener('mousedown', function(e) {
        isResizing = true;
        startX = e.clientX;
        startLeftWidth = leftPanel.offsetWidth;
        
        document.body.style.cursor = 'col-resize';
        document.body.style.userSelect = 'none';
        
        e.preventDefault();
    });

    // 结果区域上下拖拽调整高度功能
    resultResizeHandle.addEventListener('mousedown', function(e) {
        isResultResizing = true;
        startY = e.clientY;
        startTopHeight = resultTop.offsetHeight;
        
        document.body.style.cursor = 'row-resize';
        document.body.style.userSelect = 'none';
        
        e.preventDefault();
    });

    // 全局鼠标移动事件
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
}

// 处理鼠标移动
function handleMouseMove(e) {
    if (isResizing) {
        handleHorizontalResize(e);
    }
    if (isResultResizing) {
        handleVerticalResize(e);
    }
}

// 处理水平拖拽调整
function handleHorizontalResize(e) {
    const deltaX = e.clientX - startX;
    const containerWidth = container.offsetWidth;
    const handleWidth = resizeHandle.offsetWidth;
    const availableWidth = containerWidth - handleWidth;
    
    let newLeftWidth = startLeftWidth + deltaX;
    
    // 限制最小和最大宽度
    const minWidth = 300;
    const maxWidth = availableWidth * 0.7;
    
    if (newLeftWidth < minWidth) {
        newLeftWidth = minWidth;
    }
    if (newLeftWidth > maxWidth) {
        newLeftWidth = maxWidth;
    }
    
    leftPanel.style.width = newLeftWidth + 'px';
}

// 处理垂直拖拽调整
function handleVerticalResize(e) {
    const deltaY = e.clientY - startY;
    const containerHeight = resultContainer.offsetHeight;
    const handleHeight = resultResizeHandle.offsetHeight;
    const availableHeight = containerHeight - handleHeight;
    
    let newTopHeight = startTopHeight + deltaY;
    
    // 限制最小高度
    const minHeight = 150;
    const maxTopHeight = availableHeight - minHeight;
    
    if (newTopHeight < minHeight) {
        newTopHeight = minHeight;
    }
    if (newTopHeight > maxTopHeight) {
        newTopHeight = maxTopHeight;
    }
    
    resultTop.style.height = newTopHeight + 'px';
}

// 处理鼠标释放
function handleMouseUp() {
    if (isResizing) {
        isResizing = false;
        document.body.style.cursor = '';
        document.body.style.userSelect = '';
    }
    if (isResultResizing) {
        isResultResizing = false;
        document.body.style.cursor = '';
        document.body.style.userSelect = '';
    }
}

// 解析协议
function parseProtocol() {
    const messageInput = document.getElementById('messageInput').value.trim();
    if (!messageInput) {
        alert('请输入要解析的报文内容');
        return;
    }

    // 显示加载状态
    document.getElementById('loading').style.display = 'block';
    document.getElementById('jsonResult').innerHTML = '';
    document.getElementById('treeResult').innerHTML = '';
    document.getElementById('copyJsonBtn').style.display = 'none';

    // 发送请求
    fetch('/protoDecToolkit/parse', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `content=${encodeURIComponent(messageInput)}&protocolType=${selectedProtocol}`
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById('loading').style.display = 'none';
        
        if (data.success) {
            // 显示JSON格式结果（带语法高亮）
            displayJsonWithHighlight(data.formattedJson);
            
            // 构建树形结构
            buildJsonTree(JSON.parse(data.jsonResult), document.getElementById('treeResult'));
        } else {
            // 显示错误信息
            const errorHtml = `
                <div class="error-message">
                    <i class="bi bi-exclamation-triangle"></i>
                    <strong>解析失败：</strong>${data.message}
                </div>
            `;
            document.getElementById('jsonResult').innerHTML = errorHtml;
            document.getElementById('treeResult').innerHTML = errorHtml;
        }
    })
    .catch(error => {
        document.getElementById('loading').style.display = 'none';
        const errorHtml = `
            <div class="error-message">
                <i class="bi bi-exclamation-triangle"></i>
                <strong>请求失败：</strong>${error.message}
            </div>
        `;
        document.getElementById('jsonResult').innerHTML = errorHtml;
        document.getElementById('treeResult').innerHTML = errorHtml;
    });
}

// 显示带语法高亮的JSON
function displayJsonWithHighlight(jsonString) {
    const jsonContainer = document.getElementById('jsonResult');
    const copyBtn = document.getElementById('copyJsonBtn');
    
    // 创建带语法高亮的HTML
    const highlightedJson = Prism.highlight(jsonString, Prism.languages.json, 'json');
    jsonContainer.innerHTML = `<pre><code class="language-json">${highlightedJson}</code></pre>`;
    
    // 显示复制按钮
    copyBtn.style.display = 'block';
    
    // 调整JSON容器高度以适应内容
    adjustJsonContainerHeight();
}

// 调整JSON容器高度
function adjustJsonContainerHeight() {
    const jsonViewer = document.querySelector('.json-viewer');
    const resultTop = document.querySelector('.result-top');
    const resultContainer = document.querySelector('.result-container');
    
    if (jsonViewer && resultTop && resultContainer) {
        // 获取JSON内容的实际高度
        const jsonContent = jsonViewer.querySelector('pre');
        if (jsonContent) {
            const contentHeight = jsonContent.scrollHeight;
            const containerHeight = resultContainer.offsetHeight;
            const minHeight = 200; // 最小高度
            const maxHeight = Math.max(containerHeight * 0.7, minHeight); // 最大70%或最小高度
            
            // 计算合适的高度
            const idealHeight = Math.min(contentHeight + 50, maxHeight); // 内容高度+padding，但不超过最大值
            
            // 设置JSON容器高度，只影响结果区域
            resultTop.style.height = idealHeight + 'px';
            resultTop.style.flex = 'none'; // 禁用flex自动分配
            
            // 确保左侧输入区域保持固定高度
            const leftPanel = document.querySelector('.left-panel');
            if (leftPanel) {
                leftPanel.style.height = '100%';
            }
        }
    }
}

// 复制JSON到剪贴板
function copyJsonToClipboard() {
    const jsonText = document.getElementById('jsonResult').textContent;
    navigator.clipboard.writeText(jsonText).then(function() {
        const btn = document.getElementById('copyJsonBtn');
        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="bi bi-check"></i> 已复制';
        btn.classList.remove('btn-outline-light');
        btn.classList.add('btn-success');
        
        setTimeout(function() {
            btn.innerHTML = originalText;
            btn.classList.remove('btn-success');
            btn.classList.add('btn-outline-light');
        }, 2000);
    });
}

// 清空所有内容
function clearAll() {
    document.getElementById('messageInput').value = '';
    document.getElementById('jsonResult').innerHTML = `
        <div class="text-muted text-center py-5">
            <i class="bi bi-arrow-left-circle display-1"></i>
            <p class="mt-3">请选择协议类型并输入报文内容，然后点击解析按钮</p>
        </div>
    `;
    document.getElementById('treeResult').innerHTML = `
        <div class="text-muted text-center py-5">
            <i class="bi bi-table display-1"></i>
            <p class="mt-3">解析结果将以表格结构显示</p>
        </div>
    `;
    document.getElementById('copyJsonBtn').style.display = 'none';
    
    // 重置JSON容器高度
    const resultTop = document.querySelector('.result-top');
    if (resultTop) {
        resultTop.style.height = '50%';
        resultTop.style.flex = '';
    }
}

// 构建JSON表格结构
function buildJsonTree(obj, container) {
    container.innerHTML = '';
    
    // 创建表格容器
    const tableContainer = document.createElement('div');
    tableContainer.className = 'table-container';
    
    // 创建表格
    const table = document.createElement('table');
    table.className = 'table table-sm table-hover json-table';
    
    // 创建表头
    const thead = document.createElement('thead');
    thead.innerHTML = `
        <tr>
            <th style="width: 300px; min-width: 300px;">属性</th>
            <th style="width: auto;">值</th>
        </tr>
    `;
    table.appendChild(thead);
    
    // 创建表体
    const tbody = document.createElement('tbody');
    
    function buildTableRows(key, value, level = 0) {
        const rows = [];
        
        if (typeof value === 'object' && value !== null) {
            // 对象或数组类型
            const row = document.createElement('tr');
            row.className = 'table-primary';
            
            const keyCell = document.createElement('td');
            keyCell.style.paddingLeft = (level * 20 + 10) + 'px';
            keyCell.innerHTML = `
                <div class="d-flex align-items-center">
                    <i class="bi bi-folder me-2"></i>
                    <strong>${key}</strong>
                    <span class="badge bg-secondary ms-2">${Array.isArray(value) ? 'Array' : 'Object'}</span>
                </div>
            `;
            
            const valueCell = document.createElement('td');
            valueCell.innerHTML = `<span class="text-muted">${Array.isArray(value) ? `[${value.length} 项]` : '{...}'}</span>`;
            
            row.appendChild(keyCell);
            row.appendChild(valueCell);
            rows.push(row);
            
            // 递归处理子项
            if (Array.isArray(value)) {
                value.forEach((item, index) => {
                    rows.push(...buildTableRows(`[${index}]`, item, level + 1));
                });
            } else {
                Object.keys(value).forEach(k => {
                    rows.push(...buildTableRows(k, value[k], level + 1));
                });
            }
        } else {
            // 基本类型
            const row = document.createElement('tr');
            
            const keyCell = document.createElement('td');
            keyCell.style.paddingLeft = (level * 20 + 10) + 'px';
            keyCell.innerHTML = `
                <div class="d-flex align-items-center">
                    <i class="bi bi-file-text me-2"></i>
                    <strong>${key}</strong>
                </div>
            `;
            
            const valueCell = document.createElement('td');
            // 根据值类型设置不同的样式
            if (typeof value === 'string') {
                valueCell.innerHTML = `<span class="text-success">"${value}"</span>`;
            } else if (typeof value === 'number') {
                valueCell.innerHTML = `<span class="text-primary">${value}</span>`;
            } else if (typeof value === 'boolean') {
                valueCell.innerHTML = `<span class="text-warning">${value}</span>`;
            } else if (value === null) {
                valueCell.innerHTML = `<span class="text-muted">null</span>`;
            } else {
                valueCell.innerHTML = `<span class="text-muted">${value}</span>`;
            }
            
            row.appendChild(keyCell);
            row.appendChild(valueCell);
            rows.push(row);
        }
        
        return rows;
    }
    
    // 构建所有行
    Object.keys(obj).forEach(key => {
        const rows = buildTableRows(key, obj[key]);
        rows.forEach(row => tbody.appendChild(row));
    });
    
    table.appendChild(tbody);
    tableContainer.appendChild(table);
    
    // 添加列宽调整功能
    addColumnResizer(tableContainer, table);
    
    container.appendChild(tableContainer);
}

// 添加列宽调整功能
function addColumnResizer(container, table) {
    const firstHeader = table.querySelector('thead th:first-child');
    const resizer = document.createElement('div');
    resizer.className = 'column-resizer';
    firstHeader.appendChild(resizer);
    
    let isResizing = false;
    let startX, startWidth;
    
    resizer.addEventListener('mousedown', function(e) {
        isResizing = true;
        startX = e.clientX;
        startWidth = firstHeader.offsetWidth;
        
        resizer.classList.add('active');
        document.body.style.cursor = 'col-resize';
        document.body.style.userSelect = 'none';
        
        e.preventDefault();
    });
    
    document.addEventListener('mousemove', function(e) {
        if (!isResizing) return;
        
        const deltaX = e.clientX - startX;
        const newWidth = Math.max(80, startWidth + deltaX); // 最小宽度80px
        
        firstHeader.style.width = newWidth + 'px';
        firstHeader.style.minWidth = newWidth + 'px';
        
        // 更新所有第一列的单元格宽度
        const firstCells = table.querySelectorAll('tbody td:first-child');
        firstCells.forEach(cell => {
            cell.style.width = newWidth + 'px';
            cell.style.minWidth = newWidth + 'px';
        });
    });
    
    document.addEventListener('mouseup', function() {
        if (isResizing) {
            isResizing = false;
            resizer.classList.remove('active');
            document.body.style.cursor = '';
            document.body.style.userSelect = '';
        }
    });
}

// 处理键盘快捷键
function handleKeyboardShortcuts(e) {
    if (e.ctrlKey || e.metaKey) {
        switch(e.key) {
            case 'Enter':
                e.preventDefault();
                document.getElementById('parseBtn').click();
                break;
            case 'Delete':
                e.preventDefault();
                document.getElementById('clearBtn').click();
                break;
        }
    }
} 